package cn.lxb.netstatagent;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 发送到collector.
 * 
 * @author liuxb
 *
 */
public class CollectorRecorder implements AddressRecorder {

	public static String jsonTemplate = "{\"address\":\"%s\",\"serviceName\":\"%s\"}";
	static String colletorUrl = System.getProperty("netstat-agent.colletor-url");
	static String serviceName = System.getProperty("netstat-agent.service-name");

	@Override
	public void record(String address) throws Exception {
		URL url = new URL(colletorUrl);
		HttpURLConnection con = null;
		try {
			con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("POST");
			con.setRequestProperty("Content-Type", "application/json; utf-8");
			// con.setRequestProperty("Accept", "application/json");
			con.setConnectTimeout(3000);
			con.setReadTimeout(5000);
			con.setDoOutput(true);

			String requestJson = String.format(jsonTemplate, address, serviceName);
			LogUtil.debug("requestJson:" + requestJson);

			try (OutputStream os = con.getOutputStream()) {
				byte[] input = requestJson.getBytes(StandardCharsets.UTF_8);
				os.write(input, 0, input.length);
				os.flush();
			}

			// 获取响应代码
			int responseCode = con.getResponseCode();
			LogUtil.debug("Response Code: " + responseCode);

			// 读取响应数据
			if (responseCode == HttpURLConnection.HTTP_OK) {
				try (BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
					String line;
					StringBuilder response = new StringBuilder();

					while ((line = reader.readLine()) != null) {
						response.append(line);
					}

					LogUtil.debug("Response Data: " + response.toString());
				}
			} else {
				LogUtil.error("POST request failed.");
			}
		} finally {
			// 关闭连接
			if (con != null) {
				con.disconnect();
			}
		}
	}

}
